$(function(){
	addUser();
	// 判断用户是不是已经登录
	function addUser(){
		var user = $('#Marking').val();
		if(user!=''){
			loadUser();
		}
	}
	// 用户的登录成功或者已经登录，去加载用户的信息
	function loadUser(){
		var name = $.cookie("uname");
		var img = $.cookie("img");
		$(".mask").toggle();
		$(".name p").html(name);
		$("#showName").addClass("center");
		$(".head img").attr('src',img);
		$("#form").hide();
		// 获取好友列表
        getHailFellow();
        // 建立ws连接
        openWS();
	}
	
	$("#btn").click(function(){
		$.ajax({
			"url":"UserLoginServlet.do",
			"type":"post",
			"data":$("#myform").serialize(),
			"dataType":"json",
			"success":Ok,
			"error":function(){
				alert("错误!");
			}
		});
		
		function Ok(data){
			if(data == true){
				loadUser();
			}else{
				console.log(data);
			}
		}
	});
	

    // 获取好友列表
    function getHailFellow() {
        var uid = $.cookie('uid');
        $.post('/JSPing/HailFellowServlet', 'id=' + uid, function (data) {
            var $friends = $('#friends');
            $(data).each(function (index, item) {
            	
            	/*
				 * <div class="friend"> <img src="img/1_copy.jpg" /> <p>
				 * <strong>Miro Badev</strong> <span>mirobadev@gmail.com</span>
				 * </p> <div class="status available"></div> </div>
				 */
            	
            	var friend = "<div class='friend' data-id='"+item.uid+"'><img src='"+item.image+"'><p><strong>"+item.uname+"</strong><span>个性签名</span><span class='num'>0</span></p><div class='status available'></div></div>";
            	
            	$friends.append(friend);
            });
        }, 'json');
    }

    var ws;
    
    //窗口关闭时主动断开连接
    window.onbeforeunload = function(){
		ws.close();
	}
    
    // 建立连接websocket连接
    function openWS(){
    	var uid = $.cookie('uid');
        
    	ws = new WebSocket('wss://' + window.location.host + '/JSPing/websocket/' + uid);
        
        ws.onopen = function () {
            // addMag('系统','现在','连接成功');
        	//alert('链接成功!');
        };
        
        //接受消息
        ws.onmessage = function (msg) {
			var jsonmes = JSON.parse(msg.data);
			
			var str = JSON.stringify(jsonmes);
			
			var num = $("[data-id="+jsonmes.fuid+"]").find('span[class=num]');
			num.text(parseInt(num.text())+1);
			num.show();
			
			var $t = $(".friend:eq(0)");
			$("[data-id="+jsonmes.fuid+"]").insertBefore($t);
			
			
			//缓存一条消息
			cache(0,jsonmes.fuid,str);
			
//			var item = localStorage.getItem(jsonmes.fuid);
//
//			if(item==null){
//				console.log(str);
//				localStorage.setItem(jsonmes.fuid,str);
//			}else{
//				var ping = localStorage.getItem(jsonmes.fuid);
//				localStorage.setItem(jsonmes.fuid,ping+"%"+str);
//			}
			
            addMag(jsonmes.time,jsonmes.msg,0);
            console.log(msg.data);
        }
        ws.onclose = function (mess) {
            // addMag('系统','现在','断开连接');
        }
    }

    function pend(){
    	var mess = $('#mes').val();
		var id = $('#portrait').attr('data-id');
		
		var myDate = new Date();//获取系统当前时间
		var hh = myDate.getHours(); //获取当前小时数(0-23)
		var mm = myDate.getMinutes(); //获取当前分钟数(0-59)
		var ss = myDate.getSeconds(); //获取当前秒数(0-59)
		var hms = hh+":"+mm+":"+ss;
		
        var jme = "{\"fuid\":\""+id+"\",\"msg\":\""+mess+"\",\"time\":\""+hms+"\"}";
        
        cache(1,id,jme);
        
        addMag(hms,mess,1);
        console.log(jme);
		ws.send(jme);
		$('#mes').val(' ');
    }
    
    
    $('#mes').keyup(function(e){
    	if(e.keyCode == 13){
    		pend();
    	}
    });
    
    $('#send').click(function () {
    	pend();
    });
    
    //缓存一条消息
    function cache(p,id,message){
    	var item = localStorage.getItem(id);
		if(item==null){
			console.log(message);
			localStorage.setItem(id,message+p);
		}else{
			var ping = localStorage.getItem(id);
			localStorage.setItem(id,ping+"%"+message+p);
		}
    }
    
    // 添加一条消息
    function addMag(time='默认',mess='默认消息',direction='1'){
        // direction 1 是自己发的，0是好友发的
    	
    	// 自己发的
    	if(direction==1){
    		/*
			 * <div class="message right1"> <img src="img/2_copy.jpg" /> <div
			 * class="bubble"> Can you share a link for the tutorial? <div
			 * class="corner"></div> <span>1 min</span> </div> </div>
			 */
    		var img = $.cookie('img');
    		var messages = "<div class='message right1'><img src='"+img+"' /><div class='bubble'>"+mess+"<div class='corner'></div><span>"+time+"</span></div></div>";
    		
    		$('#chat-messages').append(messages);
    		
    	}else if(direction==0){
    		var img = $('#portrait').attr('src');
	   		var messages = "<div class='message'><img src='"+img+"' /><div class='bubble'>"+mess+"<div class='corner'></div><span>"+time+"</span></div></div>";
	   		$('#chat-messages').append(messages);
    	}

    }

});